/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-5-1 下午7:30 Created by dwzhang
 */
package com.jade.framework.base.criterion;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * 查询条件工具类。
 *
 * @author dwzhang
 * @version 1.0 13-5-1 下午7:30
 */
public class CriterionUtils
{
    public static <T> Criteria addEqual(Criteria criteria, String entity, String name, T value)
    {
        return criteria.add(Restrictions.eq(entity, name, value));
    }

    public static Criteria addOrder(Criteria criteria, String sortName, String sortType, String defaultSortName)
    {
        if (StringUtils.isBlank(sortName)) {
            sortName = defaultSortName;
        }
        if (StringUtils.isNotBlank(sortName)) {
            if (StringUtils.equalsIgnoreCase(sortType, "asc")) {
                criteria.addOrder(Order.asc(sortName));
            }
            else {
                criteria.addOrder(Order.desc(sortName));
            }
        }
        return criteria;
    }

    public static Criteria addQuery(Criteria criteria, String[] fields, String keyword, MatchMode matchMode,
                                    String[] defFields)
    {
        if (StringUtils.isBlank(keyword)) {
            return criteria;
        }

        if (fields == null) {
            fields = defFields;
        }
        if (fields == null || fields.length == 0) {
            return criteria;
        }

        if (fields.length == 1) {
            return criteria.add(getCriterion(fields[0], keyword, matchMode));
        }
        List<Criterion> criterions = new ArrayList<Criterion>(fields.length);
        for (String field : fields) {
            criterions.add(getCriterion(field, keyword, matchMode));
        }
        return criteria.add(Restrictions.or(criterions.toArray(new Criterion[fields.length])));
    }

    protected static Criterion getCriterion(String field, String keyword, MatchMode matchMode)
    {
        if (matchMode.equals(MatchMode.EXACT)) {
            return Restrictions.eq(field, keyword);
        }
        else {
            return Restrictions.like(field, keyword, matchMode);
        }
    }
}
